package com.ironmaking.Service.impl;

import com.ironmaking.DAO.YieldRateTableDAO;
import com.ironmaking.DAO.YieldRateDataDAO;
import com.ironmaking.Entity.YieldRateData;
import com.ironmaking.Entity.YieldRateTable;
import com.ironmaking.Service.Interface.IYieldRateService;
import com.ironmaking.Utils.PageUtil;
import com.ironmaking.Vo.data.YieldRateTableRowData;
import com.ironmaking.Vo.results.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class YieldRateService implements IYieldRateService {

    @Autowired
    YieldRateDataDAO yieldRateDataDAO;

    @Autowired
    YieldRateTableDAO yieldRateTableDAO;

    @Override
    public PageResult getYieldTableByYid(int yid, int page, int size) {
        Specification<YieldRateData> specification = (Specification<YieldRateData>)
                (root, criteriaQuery, criteriaBuilder) ->
                        criteriaBuilder.equal(root.get("Yid"), yid);
        return PageUtil.toPageResult(page,size,yieldRateDataDAO.findAll(specification));
//        return null;
    }

    @Override
    public int uploadingIngotTable(int uid,String tableName, List<YieldRateTableRowData> yieldRateDataTable) {
        YieldRateTable yieldRateTable = new YieldRateTable();
        yieldRateTable.setUpdateUserId(uid);
        yieldRateTable.setTableName(tableName);
        yieldRateTable.setUploadTime(new Date().getTime());
        try {
            yieldRateTable = yieldRateTableDAO.save(yieldRateTable);
            int yid = yieldRateTable.getYieldDataId();
            List<YieldRateData> yieldRateDataList = new ArrayList<>();
            for (YieldRateTableRowData yieldRateTableRowData : yieldRateDataTable) {
                yieldRateDataList.add(new YieldRateData().insertPropFromRowData(yid, yieldRateTableRowData));
            }
            yieldRateDataDAO.saveAll(yieldRateDataList);
            return yid;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
    }


}
